#!/usr/bin/python
#
"""Main page for mm2notes."""

__author__ = 'scottkirkwood@google.com (Scott Kirkwood)'

import datetime
import meeting
import logging
import meeting_page
import mm2notes
import os
import schema
import time
import util

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

import wsgiref.handlers

class Mm2Notes(webapp.RequestHandler):
    """Handling of the Mm2Notes pages."""

    @util.ForceLogin()
    def get(self):
        """Standard GET request."""
        user = users.get_current_user()

        template_values = {
            'user': user,
        }
        self.ListMeetings(user, template_values)
        path = os.path.join(os.path.dirname(__file__), 'index.html')
        body = template.render(path, template_values)
        self.response.out.write(body)

    def ListMeetings(self, user, vals):
        today = datetime.date.today()
        if user:
          logging.info('Fetching meetings for %r' % user.email())
          q = schema.UserToMeeting.gql('WHERE email=:1 ORDER BY timestamp DESC',
                  user.email())
        else:
          q = []
        vals['meetings'] = []
        for row in q:
            logging.info('Meeting %r' % row.topic)
            vals['meetings'].append(dict(key=row.meeting.key(), 
                    topic=row.topic, attendees=row.attendees))

    @util.ForceLogin()
    def post(self):
        file_contents = self.request.get_all('mmfile')
        file_name = self.request.get('mmfile')
        user = users.get_current_user()

        meet = meeting.Meeting()
        meet.add_meeting(user, file_name, '\n'.join(file_contents))
        self.redirect('/')



def main():
    application = webapp.WSGIApplication([
        ('/', Mm2Notes),
        ('/meeting/(.*)', meeting_page.Meeting),
        ('/delete', meeting.DeleteMeeting),
        ('/.*', Mm2Notes),
        ])
    wsgiref.handlers.CGIHandler().run(application)


if __name__ == '__main__':
    main()
